package com.aceitunaproject.server;

import java.io.Serializable;
import java.util.Properties;
import java.util.logging.Logger;

import com.aceitunaproject.server.player.Player;
import com.sun.sgs.app.AppListener;
import com.sun.sgs.app.ClientSession;
import com.sun.sgs.app.ClientSessionListener;

/**
 * Application listener for handling user logins and application initialization.
 * 
 * @author Maciej Miechowicz
 */
public class AceitunaAppListener implements AppListener, Serializable {

	private static final long serialVersionUID = -907468195733550481L;

	/**
	 * Handles application initialization
	 * 
	 * @param props
	 *            application properties
	 */
	@Override
	public void initialize(Properties props) {

		// initializes managers
		AceitunaContext.initializeManagers();

		// initializes world
		if (ServerConfiguration.getInitializer().Initialize()) {
			Logger.getLogger(this.getClass().getName()).info(
					"World successfully initialized");
		} else {
			Logger.getLogger(this.getClass().getName()).info(
					"World could not be initialized");
		}

	}

	/**
	 * Handles user login
	 * 
	 * @param session
	 *            user session
	 */
	@Override
	public ClientSessionListener loggedIn(ClientSession session) {
		Player player = AceitunaContext.getPlayerManager().getPlayer(session);

		Logger.getLogger(this.getClass().getName()).info(
				session.getName() + " logging in");
		player.setSession(session);

		return new PlayerListener(player);
	}

}
